package conf

import (
	"flag"
	"fmt"
	"io/ioutil"
	"os"
	"path"

	"gopkg.in/yaml.v2"
)

var (
	WorkSpace string // config

	ServerInfo *serverModel // server config information

	ConfigInfo *configModel // all server config information
)

//server config will used in file variables.go

type configModel struct {
	Server *serverModel `yaml:"server"`
	Mongo  *mongoModel  `yaml:"mongo"`
}

type mongoModel struct {
	Address  string `yaml:"address"`
	Database string `yaml:"database"`
}

//serverModel get server information from config.yml

type serverModel struct {
	Mode string `yaml:"mode"` // run mode

	Host string `yaml:"host"` // server host

	Port string `yaml:"port"` // server port
}

// LoadConfigInformation load config information for application

func LoadConfigInformation(configPath string) (err error) {

	var (
		filePath string

		wr string
	)

	if configPath == "" {

		wr, _ = os.Getwd()

		wr = path.Join(wr, "conf")

	} else {

		wr = configPath

	}

	WorkSpace = wr

	filePath = path.Join(WorkSpace, "config.yml")
	configData, err := ioutil.ReadFile(filePath)
	if err != nil {

		fmt.Printf(" config file read failed: %s", err)

		os.Exit(-1)

	}

	err = yaml.Unmarshal(configData, &ConfigInfo)

	if err != nil {

		fmt.Printf(" config parse failed: %s", err)

		os.Exit(-1)

	}

	// server information

	ServerInfo = ConfigInfo.Server

	return nil

}

func InitConf() {
	var err error

	fPath, _ := os.Getwd()

	fPath = path.Join(fPath, "conf")

	configPath := flag.String("c", fPath, "config file path")
	flag.Parse()

	err = LoadConfigInformation(*configPath)
	fmt.Println("===========初始化配置加载成功=========")
	fmt.Printf("Server:%+v\nMongo:%+v\n", ConfigInfo.Server, ConfigInfo.Mongo)
	if err != nil {
		return
	}
}
